package com.sanjiahantang.youjiarole.module.decorate.presenters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;


import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseBean;
import com.sanjiahantang.youjiarole.base.BaseMvpActivity;
import com.sanjiahantang.youjiarole.base.BaseMvpPresenter;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.base.CallBack;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.city.models.ICityModel;
import com.sanjiahantang.youjiarole.module.city.models.impl.CityModel;
import com.sanjiahantang.youjiarole.module.common.beans.ConditionBean;
import com.sanjiahantang.youjiarole.module.common.beans.FileBean;
import com.sanjiahantang.youjiarole.module.common.beans.StringBean;
import com.sanjiahantang.youjiarole.module.common.models.IFileModel;
import com.sanjiahantang.youjiarole.module.common.models.impl.FileModel;
import com.sanjiahantang.youjiarole.module.common.views.impl.MainActivity;
import com.sanjiahantang.youjiarole.module.decorate.beans.DecorateDicBean;
import com.sanjiahantang.youjiarole.module.decorate.beans.DecorateManageBean;
import com.sanjiahantang.youjiarole.module.decorate.models.IDecorateModel;
import com.sanjiahantang.youjiarole.module.decorate.models.impl.DecorateModel;
import com.sanjiahantang.youjiarole.module.decorate.views.DecorateManageView;
import com.sanjiahantang.youjiarole.module.decorate.views.impl.DecorateDetailActivity;
import com.sanjiahantang.youjiarole.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiarole.utils.SPUtils;

import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by zy on 2017/9/14.
 */

public class DecorateManagePresenter extends BaseMvpPresenter<DecorateManageView> {

    private IDecorateModel decorateModel;
    private FragmentManager fragmentManager;
    private FragmentTransaction ft;
    private CommonNavigatorAdapter tabAdapter;
    private List<DecorateManageBean.Data> tabList;
    private DecorateManageView.BindPageListener bindPageListener;
    private QuickAdapter<DecorateManageBean.Step> flowAdapter;
    private DecorateManageView.OnLoadListener onLoadListener;
    private ICityModel cityModel;
    private BaseView.OnLoadListener detailOnLoadListener;
    private IFileModel fileModel;

    public DecorateManagePresenter(){
        decorateModel = new DecorateModel();
        tabList = new ArrayList<>();
        cityModel = new CityModel();
        fileModel = new FileModel();
    }
    public void setFragmentManager(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
    }

    public void searchProjectInfoForRole(final Context context, String requireId, final BaseView.OnLoadListener listener) {
        detailOnLoadListener = listener;
        Map<String,String> params = new HashMap<>();
        params.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        params.put(KEY_PHONE,SPUtils.get(context,SPConfig.PHONE,"").toString());
        params.put("piId",requireId);
        mView.showProgress();
        decorateModel.searchProjectInfoForRole(context, params, new CallBack<DecorateManageBean>() {
            @Override
            public void onSuccess(DecorateManageBean response, Context context, Object tag) {
                if (mView == null) return;
                hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC
                        && response.getData() != null && response.getData().size() > 0){
                    listener.onLoad(response.getData().get(0));
                }else{
                    Utils.showToast(context,"获取工程失败");
                    ((Activity)context).finish();
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                hideProgress();
                Utils.showToast(context,"获取工程失败");
            }
        });
    }


    /**
     * 注册后填写需求单页初始化
     * @param context
     */
    public void loadIndexDic(Context context) {
        Map<String,String> param = new HashMap<>();
        if (ConfigValue.DATA_KEY != null){
            param.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        }
        String phone = SPUtils.get(context, SPConfig.PHONE,"").toString();
        if (!TextUtils.isEmpty(phone)){
            param.put(KEY_PHONE,phone);
        }
        decorateModel.loadIndexDic(context,param,new LoadIndexDicCallBack());
    }

    public void setOnLoadListener(DecorateManageView.OnLoadListener onLoadListener) {
        this.onLoadListener = onLoadListener;
    }

    public void loadCityList(Context context, BaseView.OnLoadListener listener) {
        cityModel.getAllArea(context, listener);
    }

    public void saveUserRequireInfoIntention(
            final Context context,
            String name,
            int isMan,
            ConditionBean.SelectorData jobData,
            String city,
            String address,
            int hasBaby,
            int hasOld,
            ConditionBean.SelectorData doorData,
            ConditionBean.SelectorData styleData,
            String area,
            ConditionBean.SelectorData priceData,
            String preTime
    ) {
        Map<String,Object> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put(KEY_PHONE,SPUtils.get(context,SPConfig.PHONE,"").toString());
        param.put(DecorateManageView.KEY_DECORATE_NAME,name);
        param.put(DecorateManageView.KEY_DECORATE_GENDER,isMan);
        param.put(DecorateManageView.KEY_DECORATE_JOB_VALUE,jobData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_JOB_NAME,jobData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_CITY,city);
        param.put(DecorateManageView.KEY_DECORATE_ADDRESS,address);
        param.put(DecorateManageView.KEY_DECORATE_BABY,hasBaby);
        param.put(DecorateManageView.KEY_DECORATE_OLD,hasOld);
        param.put(DecorateManageView.KEY_DECORATE_DOOR_VALUE,doorData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_DOOR_NAME,doorData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_STYLE_VALUE,styleData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_STYLE_NAME,styleData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_AREA,area);
        param.put(DecorateManageView.KEY_DECORATE_PRICE_VALUE,priceData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_PRICE_NAME,priceData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_PRE_TIME,preTime);
        decorateModel.saveUserRequireInfoIntention(context,param, new CallBack<StringBean>() {
            @Override
            public void onSuccess(StringBean response, Context context, Object tag) {
                hideProgress();
                Utils.showToast(context,response.getMessage());
            }

            @Override
            public void onFailure(String message) {
                hideProgress();
                Utils.showToast(context,message);
            }
        });
    }

    public void saveUserRequireInfoForCustomer(
            final Context context,
            String name,
            int isMan,
            ConditionBean.SelectorData jobData,
            String city,
            String address,
            int hasBaby,
            int hasOld,
            ConditionBean.SelectorData doorData,
            ConditionBean.SelectorData styleData,
            String area,
            ConditionBean.SelectorData priceData,
            String preTime,
            int designStateId,
            int projectStateId,
            int supervisionStateId,
            int totalStateId,
            int id
    ) {
        Map<String,Object> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put(KEY_PHONE,SPUtils.get(context,SPConfig.PHONE,"").toString());
        param.put(DecorateManageView.KEY_DECORATE_NAME,name);
        param.put(DecorateManageView.KEY_DECORATE_GENDER,isMan);
        param.put(DecorateManageView.KEY_DECORATE_JOB_VALUE,jobData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_JOB_NAME,jobData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_CITY,city);
        param.put(DecorateManageView.KEY_DECORATE_ADDRESS,address);
        param.put(DecorateManageView.KEY_DECORATE_BABY,hasBaby);
        param.put(DecorateManageView.KEY_DECORATE_OLD,hasOld);
        param.put(DecorateManageView.KEY_DECORATE_DOOR_VALUE,doorData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_DOOR_NAME,doorData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_STYLE_VALUE,styleData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_STYLE_NAME,styleData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_AREA,area);
        param.put(DecorateManageView.KEY_DECORATE_PRICE_VALUE,priceData.getDicValue());
        param.put(DecorateManageView.KEY_DECORATE_PRICE_NAME,priceData.getDicName());
        param.put(DecorateManageView.KEY_DECORATE_PRE_TIME,preTime);

        param.put(DecorateManageView.KEY_designStateId,designStateId);
        param.put(DecorateManageView.KEY_projectStateId,projectStateId);
        param.put(DecorateManageView.KEY_supervisionStateId,supervisionStateId);
        param.put(DecorateManageView.KEY_totalStateId,totalStateId);
        param.put(KEY_ID,id);

        decorateModel.saveUserRequireInfoForCustomer(context,param, new CallBack<StringBean>() {
            @Override
            public void onSuccess(StringBean response, Context context, Object tag) {
                hideProgress();
                Utils.showToast(context,response.getMessage());
            }

            @Override
            public void onFailure(String message) {
                hideProgress();
                Utils.showToast(context,message);
            }
        });
    }

    public void indexDecorateInfoForCustomer(Context context) {
        if (TextUtils.isEmpty(ConfigValue.DATA_KEY)){
            ((MainActivity)context).setFragmentIndex(4);
            return;
        }
        Map<String,String> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put(KEY_PHONE,SPUtils.get(context,SPConfig.PHONE,"").toString());
        decorateModel.indexDecorateInfoForCustomer(context,param, new CallBack<DecorateDicBean>() {
            @Override
            public void onSuccess(DecorateDicBean response, Context context, Object tag) {
                hideProgress();
                if (response.getCode() == RESPONSE_CODE_SUC){
                    onLoadListener.loadData(response.getData());
                }else if (response.getCode() == RESPONSE_CODE_TIME_OUT){
                    ConfigValue.DATA_KEY = null;
                    SPUtils.clear(context);
                    Utils.showToast(context,"token已过期");
                    LoginActivity.logout(context);
                    try {
                        JPushInterface.cleanTags(context,0);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    return;
                }

            }

            @Override
            public void onFailure(String message) {
                hideProgress();
            }
        });
    }

    public void updateEngnieeInfo(Context context, int ppId, int priId) {
        if (detailOnLoadListener == null) return;
        Map<String,String> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put(KEY_ID,String.valueOf(ppId));
        param.put("isPass","1");
        param.put("priId","0");
        param.put("remark","");
        mView.showProgress();
        decorateModel.updateEngnieeInfo(context,param, new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                detailOnLoadListener.onLoad(CALLBACK_TYPE_RECOVER);

            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
            }
        });
    }




    private void hideProgress() {
        if (mView != null) mView.hideProgress();
    }

    public void deleteImage(Context context, final int id, final BaseView.OnLoadListener listener) {
        Map<String,String> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put("fileId",String.valueOf(id));
        mView.showProgress();
        fileModel.deletePlanFile(context,param, new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                hideProgress();
                if (response.getCode() == RESPONSE_CODE_SUC){
                    listener.onLoad(id);
                }
            }

            @Override
            public void onFailure(String message) {
                hideProgress();
            }
        });
    }

    public void cardSelect(Activity activity) {
        Intent it = new Intent(Intent.ACTION_PICK);
        it.setType("image/*");
        activity.startActivityForResult(it, INTENT_SELECT_PIC);
    }

    public void doUploadSupervisionCheckPic(Context context, Uri uri, int priId, final BaseView.OnLoadListener listener) {
        Bitmap bitmap = null;
        try {
            bitmap = Utils.getBitmapFormUri((Activity) context,uri);
            doUploadSupervisionCheckPic(context,bitmap,priId,listener);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void doUploadSupervisionCheckPic(Context context, Bitmap bitmap, int priId, final BaseView.OnLoadListener listener) {
        Map<String,String> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put("fileId","0");
        param.put("busiId",String.valueOf(priId));
        param.put("busiTypeId","supervisionCheckPic");
        param.put("fileName",System.currentTimeMillis() + ".jpg");
        param.put(KEY_FILE_BASE64_PIC, Utils.bitmapToBase64(bitmap));

        mView.showProgress();
        fileModel.uploadPlanFile(context,param, new CallBack<FileBean>() {
            @Override
            public void onSuccess(FileBean response, Context context, Object tag) {
                hideProgress();
                if (response.getCode() == RESPONSE_CODE_SUC){
                    listener.onLoad(response.getData());
                }
            }

            @Override
            public void onFailure(String message) {
                hideProgress();
            }
        });
    }

    public void updateEngnieeInfo(final Context context, int piId, int priId, String remark, int type, final BaseView.OnLoadListener listener) {
        Map<String,String> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put(KEY_ID,String.valueOf(piId));
        param.put("isPass",String.valueOf(type));
        param.put("priId",String.valueOf(priId));
        param.put("remark",TextUtils.isEmpty(remark) ? "" : remark);
        mView.showProgress();
        decorateModel.updateEngnieeInfo(context,param, new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response != null || response.getCode() == RESPONSE_CODE_SUC){
                    Utils.showToast(context,"提交成功");
                    listener.onLoad(CALLBACK_TYPE_RECOVER);
                }else{
                    Utils.showToast(context,"提交失败");
                }

            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
                Utils.showToast(context,"提交失败");
            }
        });
    }

    public void searchFieldList(Context context, int priId, final BaseView.OnLoadListener listener) {
        Map<String,String> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put("busiId",String.valueOf(priId));
        param.put("busiTypeId","supervisionCheckPic");
        mView.showProgress();
        fileModel.searchFieldList(context,param, new CallBack<FileBean>() {
            @Override
            public void onSuccess(FileBean response, Context context, Object tag) {
                if (mView == null) return;
                hideProgress();

                if (response != null && response.getCode() == RESPONSE_CODE_SUC){
                    listener.onLoad(response.getList());
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                hideProgress();
            }
        });
    }


    private class LoadIndexDicCallBack implements CallBack<DecorateDicBean>{

        @Override
        public void onSuccess(DecorateDicBean response, Context context, Object tag) {
            hideProgress();
            if (response.getCode() == RESPONSE_CODE_SUC){
                onLoadListener.loadData(response.getData());
            }
        }

        @Override
        public void onFailure(String message) {
            hideProgress();
        }
    }
}
